package fr.emse.tatiana.corpus;



import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;



import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import fr.emse.tatiana.TatianaConstants;
import fr.emse.tatiana.display.BadDisplayFile;
import fr.emse.tatiana.display.DisplayFileReader;
import fr.emse.tatiana.filter.XQuery;

/**
 * Class representing the first page of the wizard
 */

public class AddFileMainPage extends WizardPage implements Listener
{	

	// widgets on this page 
	Text travelDate;
	Combo travelMonth;
	Combo travelYear;
	Combo returnDate;
	Combo returnMonth;
	Combo returnYear;	
	Button priceButton;	
	Text fromText;
	Text toText;
	Button planeButton;
	Button carButton;


	// status variable for the possible errors on this page

	// timeStatus holds an error if the return date is before the departure date

	IStatus timeStatus;



	// holds an error is the destination and departure fields are the same

	IStatus destinationStatus;

	private Corpus corpus;
	private Text fileName;
	private String path;
	private boolean check;

	/**
	 * 
	 */
	public AddFileMainPage(Corpus corpus) {
		super("Page1");
		setTitle("Add File to Corpus");
		setDescription("Choose a file to be added to the corpus");
		this.corpus=corpus;

		//destinationStatus = new Status(IStatus.OK, "not_used", 0, "", null);	
	}



	/**
	 * @see IDialogPage#createControl(Composite)
	 */

	public void createControl(Composite parent) {
		// create the composite to hold the widgets

		GridData gd;
		Composite composite =  new Composite(parent, SWT.NULL);

		// create the desired layout for this wizard page
		GridLayout gl = new GridLayout();
		int ncol = 3;
		gl.numColumns = ncol;
		composite.setLayout(gl);

		new Label (composite, SWT.NONE).setText("File name:");						
		fileName = new Text(composite, SWT.BORDER);
		gd= new GridData(GridData.FILL_HORIZONTAL);
		gd.grabExcessHorizontalSpace = true;
		fileName.setLayoutData(gd);
		Button browseButton = new Button(composite, SWT.PUSH);
		browseButton.setText("Browse");
		browseButton.setLayoutData(new GridData(
				GridData.HORIZONTAL_ALIGN_FILL));
		browseButton.addListener(SWT.Selection, this);

		final Button togglebutton=new Button(composite,SWT.CHECK);
		togglebutton.setText("Link to the file");
		togglebutton.setLayoutData(new GridData(
				GridData.HORIZONTAL_ALIGN_FILL));
		togglebutton.addSelectionListener(new SelectionAdapter() {
		  public void widgetSelected(SelectionEvent arg0) {
			  check=togglebutton.getSelection();
	      }
		});

		
		setControl(composite);		
	}


	/**

	 * @see Listener#handleEvent(Event)

	 */

	public void handleEvent(Event event) {

		FileDialog dialog = new FileDialog(getContainer().getShell(), SWT.OPEN); 
		path = dialog.open();
		

		fileName.setText(path);
		// Show the most serious error

		//applyToStatusLine(findMostSevere());

		getWizard().getContainer().updateButtons();

	}



	/*
	 * Returns the next page.
	 * Saves the values from this page in the model associated 
	 * with the wizard. Initializes the widgets on the next page.
	 */



	@Override
	public IWizardPage getNextPage() {    		
		saveDataToModel();		
		AddFileSynchroPage page = ((AddFileWizard)getWizard()).synchronisefile;
		page.onEnterPage();
		return page;
	}



	/**
	 * @see IWizardPage#canFlipToNextPage()
	 */
	@Override
	public boolean canFlipToNextPage() {
//		if (getErrorMessage() != null) return false;
		if (isTextNonEmpty(fileName))
			return true;

		return false;
	}



	/*

	 * Saves the uses choices from this page to the model.

	 * Called on exit of the page

	 */

	private void saveDataToModel() {
		AddFileWizard wizard = (AddFileWizard)getWizard();

		String replayer = "Video"; // default
		int type = CorpusFile.VIDEO; // default

		if (path.endsWith(".xml")) { 
			replayer = "Coffee";
			type = CorpusFile.XML;
			// TODO z later sucks as a way of identifying files
		} else if (path.endsWith(".utf8")) {
			replayer = "Drew";
			type = CorpusFile.FORESTXML;
		} else if (path.endsWith(".csv")) {
			replayer = "None";
			type = CorpusFile.CSV;
		} else if (path.endsWith(".seg")) {
			replayer = "None";
			type = CorpusFile.SEG;
		} else if (path.endsWith(".audioseg")) {
			replayer = "None";
			type = CorpusFile.AUDIOSEG;
		} 
		wizard.cf = new CorpusFile(path, type, replayer,0,0,0);
		CorpusFile cf = wizard.cf;
		if (wizard.cf.getType() != CorpusFile.VIDEO) {
			Vector<String> params = new Vector<String>();
			params.add(cf.getXmlFileURI());
			params.add(cf.getReplayer());
			IProject project = ResourcesPlugin.getWorkspace().getRoot().getProject(TatianaConstants.TATIANA_PROJECT_NAME);
			String filter = project.getFolder(TatianaConstants.SCRIPTS_FOLDER_NAME).getFile("get-dates-from-tracefile"+".xq").getLocation().toString();
			try {
				String resultpath = new XQuery(filter, params.toArray()).getName();
				DisplayFileReader reader = new DisplayFileReader(resultpath);
				reader.selectFirstItem();
				long first = reader.getLongValue("firsttime",BadDisplayFile.MISSINGFIELD);
				long last = reader.getLongValue("lasttime",BadDisplayFile.MISSINGFIELD);
				cf.setFirstTime(first);
				cf.setLastTime(last);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (BadDisplayFile e) {
				cf.setReplayer("None");
			}	
		}
	}




	/**

	 * Applies the status to the status line of a dialog page.

	 */

	private void applyToStatusLine(IStatus status) {
		String message= status.getMessage();
		if (message.length() == 0) message= null;
		switch (status.getSeverity()) {
		case IStatus.OK:
			setErrorMessage(null);
			setMessage(message);
			break;
		case IStatus.WARNING:
			setErrorMessage(null);
			setMessage(message, IMessageProvider.WARNING);
			break;				
		case IStatus.INFO:
			setErrorMessage(null);
			setMessage(message, IMessageProvider.INFORMATION);
			break;			
		default:
			setErrorMessage(message);
		setMessage(null);
		break;		
		}
	}	



	private static boolean isTextNonEmpty(Text t) {
		String s = t.getText();
		if ((s!=null) && (s.trim().length() >0)) return true;
		return false;
	}	



	private void createLine(Composite parent, int ncol) {
		Label line = new Label(parent, SWT.SEPARATOR|SWT.HORIZONTAL|SWT.BOLD);
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalSpan = ncol;
		line.setLayoutData(gridData);
	}	

}


